package com.hmall.search.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.feign.client.ItemClient;
import com.hmall.feign.dto.Item;
import com.hmall.feign.dto.PageDTO;
import com.hmall.search.constants.ESConstants;
import com.hmall.search.document.ItemDoc;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/search")
public class DocumentController {


    @Resource
    private ItemClient itemClient;

    @Resource
    private RestHighLevelClient client;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 批量添加文档
     * 数据量过大需要分页添加
     *
     * @param page 当前页码
     * @param size 每页数量
     */
    @GetMapping("/document/bulk")
    public void bulkDocument(@RequestParam("page") Integer page, @RequestParam Integer size) {
        while (true) {
            PageDTO<Item> pageDTO = itemClient.queryItemByPage(page, size);
            List<Item> items = pageDTO.getList();
            if (items.size() <= 0) {
                break;
            }
            // 创建 BulkRequest 对象，批量操作文档
            BulkRequest bulkRequest = new BulkRequest();
            items.forEach(item -> {
                // 下架商品跳过
                if (item.getStatus() == 2) {
                    return;
                }
                // 将 Iterm 转换为文档对象 ItermDoc
                ItemDoc doc = new ItemDoc(item);
                // 添加新增请求
                try {
                    bulkRequest.add(new IndexRequest(ESConstants.ES_INDEX_NAME) // 指定索引名称
                            // 指定文档的ID
                            .id(String.valueOf(doc.getId()))
                            // 将文档转为json格式
                            .source(MAPPER.writeValueAsString(doc), XContentType.JSON));
                } catch (JsonProcessingException e) {
                    log.error("json 序列化失败 => , {}", e.getMessage());
                }

            });
            // 发送请求，批量添加文档
            try {
                BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
                log.info("第 {} 次, add document is {}", page, response.status());
                page++;
            } catch (IOException e) {
                log.error("添加文档失败, => {}", e.getMessage());
            }
        }
    }
}
